<template>
  <div class="wapper">
    <div @click="show = true" class="value">{{valueMirror}}</div>

    <van-popup
      v-model="show"
      safe-area-inset-bottom
      close-on-popstate
      position="bottom"
      get-container="body"
    >
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        :show-toolbar="false"
        :formatter="formatter"
      />
    </van-popup>
  </div>
</template>

<script>
import { DatetimePicker, Popup } from 'vant';
import dayjs from 'dayjs';

export default {
  name: 'PickerDateOne',
  components: {
    [DatetimePicker.name]: DatetimePicker,
    [Popup.name]: Popup
  },
  model: {
    event: 'change'
  },
  props: {
    value: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      show: false,
      currentDate: new Date(),
    }
  },
  computed: {
    valueMirror: {
      get: function () {
        return this.value
      },
      set: function (val) {
        this.$emit('change', val)
      }
    }
  },
  watch: {
    show(val) {
      if (val) {
        this.currentDate = dayjs(this.valueMirror).toDate()
      }
    },
    currentDate(val, oldVal) {
      if (val === oldVal) return
      this.valueMirror = dayjs(val).format('YYYY-MM-DD')
    }
  },
  methods: {
    formatter(type, val) {
      if (type === 'year') {
        return `${val}年`;
      } else if (type === 'month') {
        return `${val}月`;
      } else if (type === 'day') {
        return `${val}日`;
      }
      return val;
    }
  },
  created() {
    if (!this.valueMirror) this.valueMirror = dayjs(this.currentDate).format('YYYY-MM-DD')
  }
}
</script>

<style lang="less" scoped>
.wapper,
.value {
  width: 100%;
  height: 100%;
  text-align: center;
}
/deep/.van-popup--bottom {
  height: 50% !important;
}
</style>